import java.util.concurrent.*;

/**
 * @Author: tgy
 * @Date: 2020-07-29 10:06
 */

class CrossRun{


    private BlockingQueue blockingQueue;

    private volatile int num = 0;

    public CrossRun(BlockingQueue blockingQueue){

        this.blockingQueue = blockingQueue;
    }

    public void increment(){

        try {

            this.blockingQueue.put(1);


        }catch (Exception e){

        }

    }

    public void decrement(){

        try {

            System.out.println(this.blockingQueue.take());

        }catch (Exception e){

        }
    }


}

public class BlockingQueueTest {

    public static void main(String[] args) throws Exception{


        Executors.newFixedThreadPool(3);
//        blockingQueue01();
        CrossRun crossRun = new CrossRun(new SynchronousQueue());

        for (int i = 0; i < 10; i++) {

            new Thread(()->{

                crossRun.increment();
            }).start();
        }
        for (int i = 0; i < 10; i++) {

            new Thread(()->{

                crossRun.decrement();
            }).start();
        }
    }

    private static void blockingQueue01() {
        ArrayBlockingQueue<Runnable> runnables = new ArrayBlockingQueue<Runnable>(10);
        LinkedBlockingQueue<Object> objects = new LinkedBlockingQueue<>();

        SynchronousQueue<Object> objects1 = new SynchronousQueue<>();

        new Thread(()->{

            try {

                objects1.put(11);

                System.out.println("1111");


            }catch (Exception e){

            }
        }).start();

        new Thread(()->{


            try {

                TimeUnit.SECONDS.sleep(2);
                System.out.println(objects1.take());
                System.out.println("222");
            }catch (Exception e){

            }
        }).start();
//        System.out.println(objects1.take());
//        System.out.println("2222");
//        objects1.put(22);
        while (Thread.activeCount() > 2){

            Thread.yield();
        }
    }
}
